﻿using Grundy.Common;
using Grundy.Entity;
using Grundy.Message;

namespace Grundy.Licensing.Server
{
    public class LicensingStrategyFactory
    {
        private readonly ExecutionCounter _executionCounter;

        protected LicensingStrategyFactory(){}

        public LicensingStrategyFactory(ExecutionCounter executionCounter)
        {
            _executionCounter = executionCounter;
        }


        public virtual ILicensingStrategy GetLicensingStrategyForLicense(License license, LicenseEntitlementValidity licenseEntitlementValidity, FeatureIdentificationKey key)
        {
            if (license is CountedFloatingLicense)
            {
                var countedFloatingLicense = (CountedFloatingLicense) license;
                if (countedFloatingLicense.LimitType == FloatingLicenseLimitType.Concurrency)
                {
                    return new FloatingCountedConcurrentSessionsStrategy(countedFloatingLicense, licenseEntitlementValidity, key);
                }
                if (countedFloatingLicense.LimitType == FloatingLicenseLimitType.Execution)
                {
                    return new ExecutionCountConcurrentSessionsStrategy(_executionCounter, countedFloatingLicense, licenseEntitlementValidity, key);
                }
                throw new UnexpectedApplicationException("Unknown counted license type: {}. Do not know a licensing strategy for this type.".FormatWith(countedFloatingLicense.LimitType));
            }
            if (license is UncountedFloatingLicense)
            {
                return new UncountedConcurrentSessionsStrategy(license, licenseEntitlementValidity, key);
            }
            throw new UnexpectedApplicationException("Unknown License Type: {}. Do not know a licensing strategy for this type.".FormatWith(license.GetType()));
        }
    }
}